package com.danieltoms.gcSync.screens;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.GaugeField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.DialogFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.PopupScreen;

import com.danieltoms.gcSync.GcSync;
import com.danieltoms.gcSync.GcSyncStore;
import com.danieltoms.gcSync.SyncStatus;
import com.danieltoms.gcSync.SyncThread;
import com.danieltoms.gcSync.google.GoogleDataStore;
import com.danieltoms.gcSync.google.feed.GoogleContactFeed;
import com.danieltoms.gcSync.resources.GcSyncResResource;
import com.danieltoms.gcSync.util.DateUtil;

public class StatusScreen extends MainScreen implements FieldChangeListener
{
	private boolean _manualSync = false;

	private PopupScreen _progressPopup;
	private GaugeField _gaugeField;
	LabelField _statusLabel = null;
	ButtonField _hideButton = null;
	
	public LabelField getStatusLabelField()
	{
		return _statusLabel;
	}

	public GaugeField getGaugeField()
	{
		return _gaugeField;
	}

	public PopupScreen getProgressPopup()
	{
		return _progressPopup;
	}

	private MenuItem _helpItem = new MenuItem("Help", 10, 10)
	{

		public void run()
		{
			/*
			 * Google Name Format: Given Family | Family Given Uneven Name
			 * Split: towards family | towards given
			 */

			GoogleContactFeed gcf = new GoogleContactFeed(null);
			
			try
            {
	            gcf.printAllContacts();
            }
            catch (IOException e)
            {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
            }
		}

	};

	private void log(String s)
	{
		System.out.println(s);
	}

	private void sync()
	{
		DialogFieldManager manager = new DialogFieldManager();

		_progressPopup = new PopupScreen(manager);
		_gaugeField = new GaugeField(null, 0, 100, 0, GaugeField.NO_TEXT | GaugeField.PERCENT);
		_statusLabel = new LabelField("Connecting to Google as " + GcSyncStore.instance().getEmail());
		manager.addCustomField(_statusLabel);
		manager.addCustomField(_gaugeField);
		_hideButton = new ButtonField("Hide", ButtonField.CONSUME_CLICK);
		// cancel.setChangeListener(this);
		manager.addCustomField(_hideButton);
		_hideButton.setChangeListener(this);

		((GcSync) UiApplication.getUiApplication()).getSyncThread().start();
		StatusThread statusThread = new StatusThread(this);
		statusThread.start();
		UiApplication.getUiApplication().pushScreen(_progressPopup);

	}

	class StatusThread extends Thread
	{
		StatusScreen _screen = null;

		public StatusThread(StatusScreen screen)
		{
			_screen = screen;
		}

		public void run()
		{
			SyncThread syncThread = ((GcSync) UiApplication.getUiApplication()).getSyncThread();
			SyncStatus status = ((GcSync) UiApplication.getUiApplication()).getSyncStatus();
			// TODO while is syncing
			
			int lastCount=0;
			
			while (syncThread.isAlive())
			{
				if (_screen.getProgressPopup().isDisplayed())
					{
					// log("in status thread");
					if (status.resetProgressBar())
					{
						synchronized (UiApplication.getEventLock())
						{
							int total = status.getTotalItems();
							int curr = status.getCurrentItems();
							log("reset gauge: total: " + total + " cur: " + curr);
							_screen.getGaugeField().reset(null, 0, status.getTotalItems(), status.getCurrentItems());
	
							status.setResetProgressBar(false);
						}
	
					}
	
					synchronized (UiApplication.getEventLock())
					{
	
						_screen.getStatusLabelField().setText(status.getStatusMessage());
						
						int items = status.getCurrentItems();
						
						if(items!=lastCount)
						{
							if(items<_screen.getGaugeField().getValueMax())
								_screen.getGaugeField().setValue(status.getCurrentItems());
							
							lastCount = items;
						}
	
					}
	
					/*
					 * try { StatusThread.sleep(10); } catch (InterruptedException
					 * e) { // eat it }
					 */
				}
			}
			synchronized (UiApplication.getEventLock())
			{

				if (_screen.getProgressPopup().isDisplayed())
					_screen.getProgressPopup().close();

			}
		}
	}

	private MenuItem _syncNowItem = new MenuItem("Sync Now", 15, 15)
	{
		public void run()
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run()
				{
					sync();
				}
			});

		}
	};

	private MenuItem _optionsItem = new MenuItem("Options", 20, 20)
	{
		public void run()
		{
			UiApplication.getUiApplication().pushScreen(new OptionsScreen());
		}
	};

	private MenuItem _signOutItem = new MenuItem("Sign Out", 30, 30)
	{
		public void run()
		{
			GcSyncStore.instance().storeEmail("");
			GcSyncStore.instance().commit();
			((GcSync) UiApplication.getUiApplication()).removeContactListener();

			UiApplication.getUiApplication().pushScreen(new LoginScreen());
		}
	};

	private MenuItem _eraseGoogleDataStore = new MenuItem("Erase GoogleDataStore", 34, 34)
	{
		public void run()
		{

			GoogleDataStore.instance().erase();
			GcSyncStore.instance().storeLastSyncDate("");
			drawScreen();
		}
	};

	private MenuItem _clearContacts = new MenuItem("Erase Contacts", 35, 35)
	{
		public void run()
		{
			ContactList list;

			try
			{
				list = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

				Enumeration bbContacts = list.items();

				while (bbContacts.hasMoreElements())
				{
					Contact c = (Contact) bbContacts.nextElement();

					list.removeContact(c);
				}
			}
			catch (PIMException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			GoogleDataStore.instance().erase();
			GcSyncStore.instance().storeLastSyncDate("");
			drawScreen();
		}
	};

	private MenuItem _closeItem = new MenuItem("Close", 40, 40)
	{
		public void run()
		{
			onClose();
		}
	};

	protected void makeMenu(Menu menu, int instance)
	{
		menu.add(_helpItem);
		menu.add(_syncNowItem);
		menu.add(_optionsItem);
		menu.add(_signOutItem);
		menu.addSeparator();
		menu.add(_eraseGoogleDataStore);
		menu.add(_clearContacts);
		menu.add(_closeItem);
	}

	public StatusScreen()
	{
		super();
		drawScreen();
	}

	protected void onExposed()
	{
		drawScreen();
	}

	private void drawScreen()
	{
		// todo remove this and just keep the handle to the items
		// and update
		// them as appropriate
		this.deleteAll();
		// add title
		setTitle(new LabelField(GcSync.getMessages().getMessage(GcSyncResResource.GCSYNC_TITLE), LabelField.ELLIPSIS
				| LabelField.USE_ALL_WIDTH));

		// add sign in message
		this.add(new RichTextField("Last Successful Sync", Field.NON_FOCUSABLE));
		this.add(new SeparatorField());

		String d = GcSyncStore.instance().getLastSyncDate();

		if (d != null)
		{
			
			this.add(new RichTextField(DateUtil.parseRFC3339(d).toString(), Field.NON_FOCUSABLE));
		}
		else
			this.add(new RichTextField("Never synced", Field.NON_FOCUSABLE));

		// m_app.getSyncThread().run();
		try
		{
			ContactList list = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

			int count = 0;
			Enumeration e = list.items();
			while (e.hasMoreElements())
			{
				count++;
				e.nextElement();
			}

			this.add(new RichTextField("Contacts: " + count, Field.NON_FOCUSABLE));
		}
		catch (PIMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		if(!((GcSync)UiApplication.getUiApplication()).getSyncThread().isAlive())
		{

			SyncStatus status = ((GcSync)UiApplication.getUiApplication()).getSyncStatus();

			// if the last run status is still in memory display the statistics
			if(status.success())
			{


				if (status.getBBAdd() != 0)
				this.add(new RichTextField("BlackBerry Additions: " + status.getBBAdd(), Field.NON_FOCUSABLE));
				if (status.getBBUpdate() != 0)
					this.add(new RichTextField("BlackBerry Updates: " + status.getBBUpdate(), Field.NON_FOCUSABLE));
				if (status.getBBDelete() != 0)
					this.add(new RichTextField("BlackBerry Deletes: " + status.getBBDelete(), Field.NON_FOCUSABLE));
				if (status.getGoogleAdd() != 0)
					this.add(new RichTextField("Google Additions: " + status.getGoogleAdd(), Field.NON_FOCUSABLE));
				if (status.getGoogleUpdate() != 0)
					this.add(new RichTextField("Google Updates: " + status.getGoogleUpdate(),
							Field.NON_FOCUSABLE));

				if (status.getGoogleDelete() != 0)
					this
					.add(new RichTextField("Google Deletes: " + status.getGoogleDelete(),
							Field.NON_FOCUSABLE));

				status.setSuccess(false);

			} 
			else if(status.getStatusMessage()!=null) // we may have an error
														// message
			{
				this.add(new SeparatorField());
				this.add(new RichTextField("Last Sync Failed", Field.NON_FOCUSABLE));
				this.add(new RichTextField("Reason: " + status.getStatusMessage(), Field.NON_FOCUSABLE));
			}
		}
	}

	public boolean onClose()
	{
		System.exit(0);
		return true;
	}

	public void fieldChanged(Field field, int context)
    {
	    if(_hideButton!=null)
	    {
	    	if(field.equals(_hideButton))
	    	{
	    		this.getProgressPopup().close();    		
	    	}
	    }
    }

}
